import axios, { AxiosInstance, AxiosResponse } from "axios";
import { ElLoading, ElMessageBox } from "element-plus";

const loading = {
  instance: null as ReturnType<typeof ElLoading.service> | null,
  count: 0,
  open: function () {
    if (this.count++ === 0) {
      this.instance = ElLoading.service({
        lock: true,
        text: "Loading",
        background: "rgba(0, 0, 0, 0.5)",
      }); //开启loading
    }
  },
  close: function () {
    if (this.count-- === 1) {
      this.instance?.close(); //关闭loading
      this.instance = null;
    }
  },
};
// let loadingInstance: ReturnType<typeof ElLoading.service> | null = null;
// let loadingCount: number = 0;
const instance: AxiosInstance = axios.create({
  baseURL: "/api",
});

// 设定请求拦截器
instance.interceptors.request.use(
  (config) => {
    config.headers.Authorization = sessionStorage.getItem("token");
    loading.open();
    return config;
  },
  (error) => {
    loading.close();
    ElMessageBox.alert(error.message, "报错", { type: "error" }); // 统一错误处理
    return Promise.reject(error.message); // 返回一个失败的Promise
  }
);
// 设定响应拦截器
interface HttpResponse<T = any> {
  status: 199 | 200 | 500 | 404 | 401;
  data: T;
  message: string;
}
instance.interceptors.response.use(
  (response: AxiosResponse<HttpResponse>) => {
    const {status, statusText, data} = response;
    if (status === 200) {
      switch (data.status) {
        case 200:
          return new Promise(resolve =>
            setTimeout(() => {
              loading.close();
              resolve(response.data.data);
            }, 1000)
          );
        case 199:
        case 401:
        case 404:
        case 500:
              loading.close();
              ElMessageBox.alert(data.message, "ERROR", { type: "error" })
              throw new Error(data.message);
        default:
          const _exhaustiveCheck: never = data.status;
          return _exhaustiveCheck;
      }
    } else {
       loading.close();
       ElMessageBox.alert(data.message, "ERROR", { type: "error" });
       throw new Error(statusText);
    }
  },
  (error) => {
    loading.close(); //关闭loading
    ElMessageBox.alert(error.message, "报错", { type: "error" }); // 统一错误处理
    return Promise.reject(error.message); // 返回一个失败的Promise
  }
);

export default instance;
export const request={
  //@ts-ignore
  get:<T = null>(...args:arg[])=>instance.get(...args)as Promise<T>,
  //@ts-ignore
  post:<T = null>(...args:any[])=>instance.post(...args)as Promise<T>
}
